package com.efounder.agency.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.efounder.activity.AbActivity;
import com.efounder.agency.utils.TaskDataParser;
import com.efounder.builder.base.data.EFDataSet;
import com.efounder.builder.base.data.EFRowSet;
import com.efounder.eai.EAI;
import com.efounder.eai.data.JParamObject;
import com.efounder.eai.data.JResponseObject;
import com.efounder.forwechat.BaseApp;
import com.efounder.ospmobilelib.R;
import com.efounder.tree.bean.TreeNode;
import com.efounder.util.GlobalMap;
import com.efounder.util.LoadingDataUtilBlack;
import com.efounder.util.ToastUtil;
import com.efounder.view.titlebar.AbTitleBar;
import com.zcw.togglebutton.ToggleButton;
import com.zcw.togglebutton.ToggleButton.OnToggleChanged;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;

/**
 * 公文审批的 审批页面
 *
 * @author cherise
 */
@SuppressWarnings("unchecked")
public class OAApprovalDynamicActivity extends AbActivity implements
        OnClickListener {

    private static final String TAG = "OAApprovalDynActivity";

    private static final int REQUESTCODE_USER = 0;
    private static final int REQUESTCODE_TEXTAREA = 1;
    private LinearLayout rootLayout;
    private AbTitleBar mTitleBar;

    private List<Map<String, Object>> operationData;
    private List<ViewGroup> list;
    private List<ViewGroup> twoLeavelist;
    private List<ViewGroup> shouwenViews;// 收文管理
    private List<ViewGroup> wenjianViews;// 文件类型
    private Map<String, String[]> relatedSwitchMap;// 联动开关映射关系（控制 打开某个的同时，关闭某个）
    private Map<String, Map<String, Object>> noselectSwitchMap;// 没有默认打开的联动map
    /**
     * 一级View，开关打开的map们
     **/
    private List<Map<String, Object>> oneLevelSelectedMaps = new ArrayList<Map<String, Object>>();
    /**
     * 点击view时，记录数据
     **/
    private Map<String, Object> clickedViewReferenceMap;

    private String itemId;
    private String systemType;
    private String typeString;// 代办还是已办
    private AsyncTask<String, Integer, String> asyncTask;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        BaseApp.actManager.putActivity(TAG, this);

        setAbContentView(R.layout.oa_approval_act);
        list = new ArrayList<ViewGroup>();
        twoLeavelist = new ArrayList<ViewGroup>();
        shouwenViews = new ArrayList<ViewGroup>();
        wenjianViews = new ArrayList<ViewGroup>();

        initView();

        initData();

    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        if (asyncTask != null) {
            asyncTask.cancel(true);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            BaseApp.actManager.removeActivity(TAG);
            return false;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    private void initView() {

        mTitleBar = this.getTitleBar();
        mTitleBar.setTitleText("审批");
        mTitleBar.setLogo(R.drawable.ef_title_view_back);

        // 添加提交按钮
        Button submitButton = new Button(this);
        submitButton.setText("提交");
        submitButton.setOnClickListener(new SubmitClickListener());
        submitButton.setTextSize(16);
        submitButton.setTextColor(getResources().getColor(R.color.title_TextColor));
        submitButton.setBackgroundColor(Color.TRANSPARENT);
        mTitleBar.addRightView(submitButton);
        mTitleBar.setTitleBarGravity(Gravity.CENTER, Gravity.CENTER);

        mTitleBar.setLogoOnClickListener(this);

        rootLayout = (LinearLayout) findViewById(R.id.oa_approval_lay);
    }

    private void initData() {
        TaskDataParser taskDataParser = new TaskDataParser(this);
        EFDataSet rootDataSet = (EFDataSet) getIntent().getSerializableExtra(
                "rootDataSet");
        itemId = getIntent().getStringExtra("itemId");
        systemType = getIntent().getStringExtra("systemtype");
        typeString = getIntent().getStringExtra("type");
        // 数据
        operationData = taskDataParser.parseOperation(rootDataSet);
        createView(rootLayout, operationData);
    }

    /**
     * 提交按钮监听
     *
     * @author XinQing
     */
    private class SubmitClickListener implements OnClickListener {

        @Override
        public void onClick(View v) {
            if (oneLevelSelectedMaps == null
                    || oneLevelSelectedMaps.size() == 0) {
                Toast.makeText(OAApprovalDynamicActivity.this, "请选择需要提交的内容",
                        Toast.LENGTH_LONG).show();
                return;
            }
            // 1.获取提交数据
            // 专班的数据
            // {btntz=yes, fieldapproval=, documentid=
            // 958E878FE54DBA544825803A00349597,
            // filepath=sinopeczyyt/dep52/swgl_52.nsf,
            // userzhuanban=, btnzhuanban=zb}
            // 办理的数据
            /*
             * {xyhj=办理, nextnode=5, fieldapproval=,
			 * curusername=CN=蒙玉平/O=sinopec, btntz1=yes, spgz=2,
			 * nextstepusername=, documentid=CBC0025312C864EA48257FB9000A0311,
			 * filepath=sinopeczyyt/dep52/swgl_52.nsf}
			 */
            Map<String, String> nameValueMap = getSubmitData();
            // yqs if判断 9.29
            if (nameValueMap.containsKey("btnzhuanban")
                    && nameValueMap.get("userzhuanban").equals("")) {
                ToastUtil.showToast(OAApprovalDynamicActivity.this, "请选择转办人员");
                return;
            } else if (nameValueMap.containsKey("xyhj")
                    && nameValueMap.get("xyhj").equals("办理")
                    && nameValueMap.get("xnextstepusernameyhj").equals("")) {
                ToastUtil.showToast(OAApprovalDynamicActivity.this,
                        "请选择下一环节处理人");
                return;
            }

            // 2.将map转成服务器需要的参数
            String paramString = changeData2Param(nameValueMap);
            // 3.提交
            submit(paramString);
        }

        private Map<String, String> getSubmitData() {
            Map<String, String> nameValueMap = new HashMap<String, String>();

            for (Map<String, Object> oneLevelMap : oneLevelSelectedMaps) {
                // 1.获取一级map中的所有 name="XX" value="XX"
                nameValueMap.put((String) oneLevelMap.get("name"),
                        (String) oneLevelMap.get("value"));
                List<Map<String, Object>> twoLevelMaps = (List<Map<String, Object>>) oneLevelMap
                        .get(TaskDataParser.OPERATION_KEY_CHILD);
                for (Map<String, Object> twoLevelMap : twoLevelMaps) {
                    // 2.获取二级map中的所有 name="XX" value="XX"
                    String name = (String) twoLevelMap.get("name");
                    String value = (String) twoLevelMap.get("value");
                    if (name != null && (name.equals("btntz") || name.equals("btntz1"))) {// 是否开启短信通知
                        String checked = (String) twoLevelMap.get("checked");
                        if ("false".equals(checked)) {
                            continue;
                        }
                    }

                    for (int i = 0; i < twoLeavelist.size(); i++) {
                        // if (twoLevelMap.get("id").equals(
                        // ((Map<String, Object>) twoLeavelist.get(i)
                        // .getTag()).get("id"))) {
                        if (((Map<String, Object>) twoLeavelist.get(i).getTag())
                                .equals(twoLevelMap)) {
                            ViewGroup twoLevelview = twoLeavelist.get(i);
                            EditText editText = (EditText) twoLevelview
                                    .findViewById(R.id.editText_oa);
//                            if (value == null || value.equals("")) {
//                                value = editText.getText().toString();
//                            }
                            value  = editText.getText().toString();
                        }

                    }

                    List<Map<String, Object>> threeLevelMaps = (List<Map<String, Object>>) twoLevelMap
                            .get(TaskDataParser.OPERATION_KEY_CHILD);
                    // 3.将三级中 checked=true 的value值用 “;#” 进行拼接
                    if (threeLevelMaps != null && threeLevelMaps.size() > 0) {
                        StringBuffer buffer = new StringBuffer(value);
                        for (Map<String, Object> threeLevelMap : threeLevelMaps) {
                            if ("true".equals(threeLevelMap.get("checked")))// 过滤出
                                // checked=true
                                // 的user
                                buffer.append(threeLevelMap.get("value"))
                                        .append(";#");
                        }
                        if (buffer.length() - 2 > 0) {
                            value = buffer.substring(0, buffer.length() - 2);
                        }

                    }
                    nameValueMap.put(name, value);
                }
            }

            return nameValueMap;

        }

        // 将map转成服务器需要的参数，服务器的格式如：PO.SetValueByParamName("OA_params_forxml",
        // "btnchuanyue:cy&&userchuanyue:CN=胡瑾瑜/O=sinopec&&documentid:0D8A633FD9E56EE148257F7A00303BC0&&filepath:sinopeczyyt/dep52/swgl_52.nsf");
        private String changeData2Param(Map<String, String> map) {
            String submitResultItem = "";

            for (String key : map.keySet()) {
                System.out.println("key= " + key + " and value= "
                        + map.get(key));
                submitResultItem += (key + ":" + map.get(key) + "&&");
            }
            submitResultItem = submitResultItem.substring(0,
                    submitResultItem.length() - 2);
            return submitResultItem;
        }

        private void submit(String OA_params_forxml) {
            asyncTask = new AsyncTask<String, Integer, String>() {

                protected void onPreExecute() {
                    super.onPreExecute();
                    // 加载dialog显示
                    LoadingDataUtilBlack.show(OAApprovalDynamicActivity.this);
                }

                @Override
                protected String doInBackground(String... params) {
                    String result = "";
                    String OA_params_forxml = params[0];

                    // 创建PO
                    JParamObject PO = JParamObject.Create();
                    JResponseObject RO = null;
                    String tokenConId = GlobalMap.getProperty(
                            systemType + "Id", "");

                    PO.SetValueByParamName("WB_SYS_KEY", systemType);
                    PO.SetValueByParamName(systemType
                            + "_params_tokenIDFromMoblie", tokenConId);

                    // PO.SetValueByParamName(systemType+"_params_type", "db");
                    PO.SetValueByParamName(systemType + "_params_type",
                            typeString);
                    PO.SetValueByParamName(systemType + "_params_forxml",
                            OA_params_forxml);
                    PO.SetValueByParamName(systemType + "_params_itemId",
                            itemId);
                    PO.SetValueByParamName(systemType + "_systemmethod",
                            "SubmitHandler");

                    try {
                        // 连接服务器
                        RO = EAI.DAL.SVR("ExternalInterfaceDataService", PO);
                        Map<String, EFDataSet> map = RO.getResponseMap();
                        // 1 DataSet
                        EFDataSet rootDataSet = (EFDataSet) map.get(systemType);
                        List<EFRowSet> rowSets = rootDataSet.getRowSetArray();
                        if (rowSets != null && rowSets.size() > 0) {
                            // rowSets[0] = {_Self_RowSet=, elementname=result,
                            // elementtext=1}
                            // rowSets[1] = {_Self_RowSet=, elementname=message,
                            // elementtext=提交成功}
                            EFRowSet rowSet0 = rowSets.get(0);
                            if ("1".equals(rowSet0
                                    .getString("elementtext", "0"))) {
                                result = "success";
                            } else {
                                result = "fail";
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    return result;
                }

                protected void onPostExecute(String result) {
                    super.onPostExecute(result);
                    LoadingDataUtilBlack.dismiss();
                    if ("success".equals(result)) {
                        // TODO 1 提交成功,关闭页面，刷新列表
                        Toast.makeText(OAApprovalDynamicActivity.this, "提交成功",
                                Toast.LENGTH_LONG).show();

                        OAApprovalDynamicActivity.this.setResult(RESULT_OK);
                        // 关闭Activity
                        BaseApp.actManager.removeActivity(TAG);

                    } else {
                        Toast.makeText(OAApprovalDynamicActivity.this, "提交失败",
                                Toast.LENGTH_LONG).show();

                        // OAApprovalDynamicActivity.this.setResult(RESULT_OK);
                        // // 关闭Activity
                        // BaseApp.actManager.removeActivity(TAG);
                    }

                }

                @Override
                protected void onCancelled() {
                    super.onCancelled();
                    Log.i(TAG, "asyncTask--onCancelled");
                }
            };
            // .execute(OA_params_forxml);
            asyncTask.executeOnExecutor(Executors.newCachedThreadPool(),
                    OA_params_forxml);

        }
    }

    private void createView(LinearLayout rootLayout,
                            List<Map<String, Object>> oneLeveList) {
        // 一级-----{ minlength=0, regex=false, parent=父类元素名称-null, closevalue=bl,
        // type=radio, _Self_RowSet=, child=子元素个数-4, message=请选择操作方式,
        // submitflag=submit, title=传阅, maxlength=0, alt=, name=btnchuanyue,
        // value=cy, required=false, elementname=input, checked=false, }
        for (Map<String, Object> oneLevelMap : oneLeveList) {
            ViewGroup oneLevelView = createViewByType(oneLevelMap);

            manageOneLevelView(oneLevelView, oneLevelMap);
            rootLayout.addView(oneLevelView);
            // 加一个 空view
            rootLayout.addView(createBlankView());
            // 给textView赋值
            setTextByLevel(oneLevelView, oneLevelMap, 1);

            if (oneLevelView.getChildCount() >= 1) {
                View oneLevelHeaderView = oneLevelView.getChildAt(0);
                oneLevelHeaderView
                        .setOnClickListener(new OnHierarchyViewClickListener());
                ViewGroup oneLevelContainerView = (ViewGroup) oneLevelView
                        .getChildAt(1);
                // 二级-----{ parent=父类元素名称-input, type=user, _Self_RowSet=,
                // child=子元素个数-0, id=8d9010fb-1719-4092-9308-e979a2bef26c,
                // message=请选择传阅人员, submitflag=subuserchuanyue, userchoice=true,
                // title=选择传阅人员, default=true, alt=, name=userchuanyue, value=,
                // multi=true, isreplace=false, required=true, elementname=user,
                // filter=;;;;getallperson, }
                List<Map<String, Object>> twoLeveList = (List<Map<String, Object>>) oneLevelMap
                        .get("child");
                for (Map<String, Object> twoLevelMap : twoLeveList) {
                    // 过滤掉隐藏项
                    if ("hidden".equals((String) twoLevelMap.get("type"))) {
                        continue;
                    }
                    ViewGroup twoLevelView = createViewByType(twoLevelMap);
                    manageTwoLevelView(twoLevelView, twoLevelMap);
                    oneLevelContainerView.addView(twoLevelView);
                    // 给textView赋值
                    setTextByLevel(twoLevelView, twoLevelMap, 2);
                    if (twoLevelView.getChildCount() >= 1) {
                        View twoLevelHeaderView = twoLevelView.getChildAt(0);
                        twoLevelHeaderView
                                .setOnClickListener(new OnHierarchyViewClickListener());
                        ViewGroup twoLevelContainerView = (ViewGroup) twoLevelView
                                .getChildAt(1);
                        // 三级-----{ value=CN=李光辉/O=sinopec, parent=父类元素名称-user,
                        // readonly=true, checked=true, elementname=option,
                        // _Self_RowSet=, elementtext=李光辉, }
                        List<Map<String, Object>> threeLeveList = (List<Map<String, Object>>) twoLevelMap
                                .get("child");
                        for (Map<String, Object> threeLevelMap : threeLeveList) {
                            ViewGroup threeLevelView = createViewByType(threeLevelMap);
                            manageThreeLevelView(threeLevelView, threeLevelMap);
                            threeLevelView.setTag(threeLevelMap);
                            twoLevelContainerView.addView(threeLevelView);
                            // 给textView赋值
                            setTextByLevel(threeLevelView, threeLevelMap, 3);
                        }
                    }
                }
            }
        }
    }

    /**
     * 管理一级view
     *
     * @param oneLevelView
     * @param oneLevelMap
     */
    private void manageOneLevelView(ViewGroup oneLevelView,
                                    Map<String, Object> oneLevelMap) {
        // 1.设置tag
        String value = (String) oneLevelMap.get("value");
        // oneLevelView.setTag("oneLevelView_" + value);//oneLevelView_cy
        oneLevelView.setTag(oneLevelMap);
        list.add(oneLevelView);

        // 2.先设置toggleButton 监听
        ToggleButton toggleButton = (ToggleButton) oneLevelView
                .findViewById(R.id.state_view);
        if (toggleButton != null) {
            toggleButton
                    .setOnToggleChanged(new OneLevelOnToggleChangedListener(
                            oneLevelMap));
        }

        if ("true".equals(oneLevelMap.get("checked"))) {
            // 2.展开checked=true 元素
            expandOrCollapse(oneLevelView, true);
            // 3.组织生成联动开关映射关系
            String closevalue = (String) oneLevelMap.get("closevalue");
            if (closevalue != null) {
                String[] closeValues = closevalue.split(",");
                relatedSwitchMap = new HashMap<String, String[]>();
                relatedSwitchMap.put(value, closeValues);
                for (String key : closeValues) {
                    relatedSwitchMap.put(key, new String[]{value});
                }
            }
        } else {
            // 3.处理没有选中的情况

            noselectSwitchMap = new HashMap<String, Map<String, Object>>();
            noselectSwitchMap.put(value, oneLevelMap);

        }

    }

    private class OneLevelOnToggleChangedListener implements OnToggleChanged {
        Map<String, Object> oneLevelMap;

        public OneLevelOnToggleChangedListener(Map<String, Object> oneLevelMap) {
            super();
            this.oneLevelMap = oneLevelMap;
        }

        @Override
        public void onToggle(boolean on) {
            String valueString = (String) oneLevelMap.get("value");
            // 如果value 是 9999 代表结束流程
            if (on) {

                if ("cy".equals(valueString)) {// 如果是传阅，打开并add
                    oneLevelSelectedMaps.add(oneLevelMap);
                    return;
                } else {// 如果当前按钮不是传阅，打开当前按钮，关闭其他按钮
                    ViewGroup oneLevelView = null;
                    for (int i = 0; i < list.size(); i++) {
                        if (!list.get(i).getTag().equals(oneLevelMap)) {
                            oneLevelView = list.get(i);
                            Map<String, Object> tempMap = (Map<String, Object>) list
                                    .get(i).getTag();
                            String value1 = (String) tempMap.get("value");
                            if (!"cy".equals(value1)
                                    || ("9999".equals(valueString) && "cy"
                                    .equals(value1))) {
                                ToggleButton toggleButton = (ToggleButton) list
                                        .get(i).findViewById(R.id.state_view);
                                toggleButton.toggleOff();
                                oneLevelSelectedMaps.remove(tempMap);
                                expandOrCollapse(oneLevelView, false);
                            }
                            // else{
                            // ToggleButton toggleButton = (ToggleButton) list
                            // .get(i).findViewById(R.id.state_view);
                            // toggleButton.toggleOff();
                            // oneLevelSelectedMaps.remove(tempMap);
                            // expandOrCollapse(oneLevelView, false);
                            // }

                        }
                    }
                }

                oneLevelSelectedMaps.add(oneLevelMap);
            } else {
                if (oneLevelSelectedMaps.contains(oneLevelMap)) {
                    oneLevelSelectedMaps.remove(oneLevelMap);
                }
            }
            // if (on) {
            // ViewGroup oneLevelView = null;
            // for (int i = 0; i < list.size(); i++) {
            // if (list.get(i).getTag().equals(oneLevelMap)) {
            // // oneLevelView = list.get(i);
            // String valueString = (String) oneLevelMap.get("value");
            // if (!"cy".equals(valueString)) {
            // return;
            // }
            //
            // } else {
            // oneLevelView = list.get(i);
            // Map<String, Object> tempMap = (Map<String, Object>) list
            // .get(i).getTag();
            //
            // ToggleButton toggleButton = (ToggleButton) list.get(i)
            // .findViewById(R.id.state_view);
            // String valueString = (String) tempMap.get("value");
            // if (!"cy".equals(valueString)) {
            // // 如果不是传阅 可以关闭
            // toggleButton.toggleOff();
            // oneLevelSelectedMaps.remove(tempMap);
            // expandOrCollapse(oneLevelView, false);
            // }
            //
            // }
            // }
            //
            // oneLevelSelectedMaps.add(oneLevelMap);
            // } else {
            // if (oneLevelSelectedMaps.contains(oneLevelMap)) {
            // oneLevelSelectedMaps.remove(oneLevelMap);
            // }
            // }

            // if (on) {
            // oneLevelSelectedMaps.add(oneLevelMap);
            // }else {
            // if (oneLevelSelectedMaps.contains(oneLevelMap)) {
            // oneLevelSelectedMaps.remove(oneLevelMap);
            // }
            // }
            Log.i("", "------选中的一级Map:oneLevelSelectedMaps"
                    + oneLevelSelectedMaps.size());
        }

    }

    private void manageTwoLevelView(ViewGroup twoLevelView,
                                    Map<String, Object> twoLevelMap) {
        // 添加tag
        twoLevelView.setTag(twoLevelMap);
        // 添加点击事件
        String _default = (String) twoLevelMap.get("default");// default="true"

        View actionView = twoLevelView.findViewById(R.id.action_view);
        if (actionView == null) {
            actionView = twoLevelView.findViewById(R.id.state_view);
            if (actionView == null) {
                return;
            }
        }
        if (actionView instanceof ToggleButton) {
            ToggleButton toggleButton = (ToggleButton) twoLevelView
                    .findViewById(R.id.state_view);
            if (toggleButton != null) {

                if ("true".equals(twoLevelMap.get("checked"))) {
                    toggleButton.setToggleOn();
                } else {
                    toggleButton.setToggleOff();
                }
                toggleButton
                        .setOnToggleChanged(new TwoLevelOnToggleChangedListener(
                                twoLevelMap));
            }
            return;
        }

        if ("false".equals(_default)) {// 不可点击，变为灰色
            if (actionView instanceof ImageView) {
                ImageView actionImageView = (ImageView) actionView;
                actionImageView.setColorFilter(Color.GRAY);
            }
        } else {// 添加点击事件
            actionView.setOnClickListener(new TwoLevelActionViewClickListener(
                    twoLevelMap));
        }
    }

    private class TwoLevelOnToggleChangedListener implements OnToggleChanged {
        Map<String, Object> twoLevelMap;

        public TwoLevelOnToggleChangedListener(Map<String, Object> twoLevelMap) {
            super();
            this.twoLevelMap = twoLevelMap;
        }

        @Override
        public void onToggle(boolean on) {
            String valueString = (String) twoLevelMap.get("value");

            if (on) {
                twoLevelMap.put("checked", "true");
                // for (int i = 0; i < helpViews.size(); i++) {
                // if (!helpViews.get(i).getTag().equals(twoLevelMap)) {
                // ToggleButton toggleButton = (ToggleButton) helpViews
                // .get(i).findViewById(R.id.state_view);
                // toggleButton.setToggleOff();
                // Map<String, Object> tempMap = (Map<String, Object>) helpViews
                // .get(i).getTag();
                // tempMap.put("checked", "false");
                // }
                // }
            } else {
                twoLevelMap.put("checked", "false");
                // for (int i = 0; i < helpViews.size(); i++) {
                // if (!helpViews.get(i).getTag().equals(twoLevelMap)) {
                // ToggleButton toggleButton = (ToggleButton) helpViews
                // .get(i).findViewById(R.id.state_view);
                // toggleButton.setToggleOn();
                // Map<String, Object> tempMap = (Map<String, Object>) helpViews
                // .get(i).getTag();
                // tempMap.put("checked", "true");
                // }
                // }
            }

        }

    }

    /**
     * //三级-----{ value=CN=李光辉/O=sinopec, parent=父类元素名称-user, readonly=true,
     * checked=true, elementname=option, _Self_RowSet=, elementtext=李光辉, }
     *
     * @param threeLevelView
     * @param threeLevelMap
     */
    private void manageThreeLevelView(ViewGroup threeLevelView,
                                      Map<String, Object> threeLevelMap) {
        View actionView = threeLevelView.findViewById(R.id.action_view);
        if (actionView != null && actionView instanceof RadioButton) {
            RadioButton actionRadioButton = (RadioButton) actionView;
            boolean isReadOnly = "true".equals((String) threeLevelMap
                    .get("readonly"));
            actionRadioButton.setEnabled(!isReadOnly);
            boolean isChecked = "true".equals((String) threeLevelMap
                    .get("checked"));
            actionRadioButton.setChecked(isChecked);
            actionRadioButton
                    .setOnCheckedChangeListener(new ThreeLevelOnCheckedChangeListener(
                            threeLevelMap));
            actionRadioButton.setOnClickListener(new ThreeLevelOnClickListener(
                    threeLevelMap, actionRadioButton.isChecked()));
        }
    }

    private class ThreeLevelOnClickListener implements OnClickListener {
        Map<String, Object> threeLevelMap;
        boolean isCheck;

        public ThreeLevelOnClickListener(Map<String, Object> threeLevelMap,
                                         boolean isCheck) {
            super();
            this.threeLevelMap = threeLevelMap;
            this.isCheck = isCheck;

        }

        @Override
        public void onClick(View v) {
            if (v instanceof RadioButton) {
                RadioButton radioButton = (RadioButton) v;
                // if (radioButton.isChecked()) {
                // radioButton.setChecked(!radioButton.isChecked());
                // }
                System.out.println("点击前"
                        + (String) threeLevelMap.get("elementtext")
                        + String.valueOf(isCheck)
                        + (String) threeLevelMap.get("checked"));
                // isCheck = !isCheck;
                isCheck = !"true".equals(threeLevelMap.get("checked"));
                radioButton.setChecked(isCheck);
                if (isCheck) {
                    threeLevelMap.put("checked", "true");
                } else {
                    threeLevelMap.put("checked", "false");
                }
                System.out.println("点击后"
                        + (String) threeLevelMap.get("elementtext")
                        + String.valueOf(isCheck)
                        + (String) threeLevelMap.get("checked"));
                // threeLevelMap.put("checked", radioButton.isChecked() + "");

                // 处理接收按钮 checkbox单选的问题
                for (int i = 0; i < shouwenViews.size(); i++) {
                    //	if (i < shouwenViews.size()) {
                    if (!shouwenViews.get(i).getTag().equals(threeLevelMap)
                            && !((String) threeLevelMap.get("value"))
                            .contains("正式")) {

                        RadioButton button = (RadioButton) shouwenViews
                                .get(i).findViewById(R.id.action_view);
                        button.setChecked(false);
                        // String isString = (String) ((Map<String, Object>)
                        // shouwenViews
                        // .get(i).getTag()).get("checked");
                        // System.out.println("收文前："
                        // + (String) ((Map<String, Object>) shouwenViews
                        // .get(i).getTag()).get("elementtext")
                        // + isString);
                        ((Map<String, Object>) shouwenViews.get(i).getTag())
                                .put("checked", "false");
                        // isString = (String) ((Map<String, Object>)
                        // shouwenViews
                        // .get(i).getTag()).get("checked");
                        // System.out.println("收文后："
                        // + (String) ((Map<String, Object>) shouwenViews
                        // .get(i).getTag()).get("elementtext")
                        // + isString);

                        //}
                    }

                }
                for (int i = 0; i < wenjianViews.size(); i++) {
                    //if (i < wenjianViews.size()) {
                    if (!wenjianViews.get(i).getTag().equals(threeLevelMap)
                            && !((String) threeLevelMap.get("value"))
                            .contains("收文")) {

                        RadioButton button = (RadioButton) wenjianViews
                                .get(i).findViewById(R.id.action_view);

                        button.setChecked(false);
                        // String isString = (String) ((Map<String, Object>)
                        // shouwenViews
                        // .get(i).getTag()).get("checked");
                        // System.out.println("文件前："
                        // + (String) ((Map<String, Object>) shouwenViews
                        // .get(i).getTag()).get("elementtext")
                        // + isString);
                        ((Map<String, Object>) wenjianViews.get(i).getTag())
                                .put("checked", "false");
                        // isString = (String) ((Map<String, Object>)
                        // shouwenViews
                        // .get(i).getTag()).get("checked");
                        // System.out.println("文件后："
                        // + (String) ((Map<String, Object>) shouwenViews
                        // .get(i).getTag()).get("elementtext")
                        // + isString);
                        //	}
                    }
                }

                Log.i("",
                        "------onClick:"
                                + TaskDataParser
                                .hierarchyMap2String(threeLevelMap));
            }
        }

    }

    private class ThreeLevelOnCheckedChangeListener implements
            OnCheckedChangeListener {
        @SuppressWarnings("unused")
        Map<String, Object> threeLevelMap;

        public ThreeLevelOnCheckedChangeListener(
                Map<String, Object> threeLevelMap) {
            super();
            this.threeLevelMap = threeLevelMap;
        }

        @Override
        public void onCheckedChanged(CompoundButton buttonView,
                                     boolean isChecked) {
            Log.i("", "------onCheckedChanged");
        }

    }

    private class TwoLevelActionViewClickListener implements OnClickListener {
        HashMap<String, Object> twoLevelMap;

        public TwoLevelActionViewClickListener(Map<String, Object> twoLevelMap) {
            super();
            this.twoLevelMap = (HashMap<String, Object>) twoLevelMap;
        }

        @Override
        public void onClick(View v) {
            // 点击跳转 type="user" default="true" || type="textarea"
            clickedViewReferenceMap = twoLevelMap;
            String type = (String) twoLevelMap.get("type");
            if ("user".equals(type)) {
                Intent intent = new Intent(OAApprovalDynamicActivity.this,
                        DeptUserTreeActivity.class);
                // intent.putExtra("twoLevelMap", twoLevelMap);
                intent.putExtra("type", type);
                intent.putExtra("systemType", systemType);
                intent.putExtra("filter", (String) twoLevelMap.get("filter"));
                intent.putExtra("title", (String) twoLevelMap.get("title"));
                startActivityForResult(intent, REQUESTCODE_USER);
            } else if ("textarea".equals(type) || "text".equals(type)) {
                String commonphraseID = (String) twoLevelMap.get("id");
                if (commonphraseID != null && !"".equals(commonphraseID)) {
                    Intent intent = new Intent(OAApprovalDynamicActivity.this,
                            ApprovalOpinion.class);
                    intent.putExtra("commonphraseID", commonphraseID);
                    intent.putExtra("type", type);
                    intent.putExtra("systemType", systemType);
                    startActivityForResult(intent, REQUESTCODE_TEXTAREA);
                }
            } else if ("group".equals(type)) {
                Intent intent = new Intent(OAApprovalDynamicActivity.this,
                        DeptUserTreeActivity.class);
                // intent.putExtra("twoLevelMap", twoLevelMap);
                intent.putExtra("type", type);
                intent.putExtra("systemType", systemType);
                intent.putExtra("filter", (String) twoLevelMap.get("filter"));
                intent.putExtra("title", (String) twoLevelMap.get("title"));
                startActivityForResult(intent, REQUESTCODE_USER);
            }
        }
    }

    private void setTextByLevel(ViewGroup levelView,
                                final Map<String, Object> levelMap, int level) {
        TextView textView = (TextView) levelView.findViewById(R.id.textView_oa);
        switch (level) {
            case 1:
                textView.setText((String) levelMap.get("title"));
                break;
            case 2:
                textView.setText((String) levelMap.get("title"));
                if ("textarea".equals((String) levelMap.get("type"))
                        || "text".equals((String) levelMap.get("type"))) {
                    twoLeavelist.add(levelView);
                    EditText editText = (EditText) levelView
                            .findViewById(R.id.editText_oa);
                    if (textView != null) {
                        String alt = (String) levelMap.get("alt");
                        String value = (String) levelMap.get("value");
                        if (value != null && !value.equals("")) {
                            editText.setText(value);
                        } else {
                            editText.setHint(alt);
                        }

                    }
                }
                String elementname = (String) levelMap.get("elementname");
                if ("select".equals(elementname)) {// 说明是接收这个按钮
                    TextView textView1 = (TextView) levelView
                            .findViewById(R.id.textView_oa);
                    List<Object> child = (List<Object>) levelMap.get("child");
                    int size = child.size();
                    if (size == 2) {
                        textView1.setText("文件类型");
                    } else {
                        textView1.setText("收文类型");
                    }
                }
                break;
            case 3:
                textView.setText((String) levelMap
                        .get(TaskDataParser.KEY_ELEMENTTEXT));
                break;

            default:
                break;
        }
    }

    /**
     * 为了得到传回的数据，必须在前面的Activity中（指MainActivity类）重写onActivityResult方法
     * <p>
     * requestCode 请求码，即调用startActivityForResult()传递过去的值 resultCode
     * 结果码，结果码用于标识返回数据来自哪个新Activity
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK && data != null) {
            switch (requestCode) {
                case REQUESTCODE_USER:
                    List<TreeNode> selectedNodes = (List<TreeNode>) data
                            .getSerializableExtra("result");
                    // 1.操作数据
                    List<Map<String, Object>> userMaps = (List<Map<String, Object>>) clickedViewReferenceMap
                            .get(TaskDataParser.OPERATION_KEY_CHILD);
                    threeLevel_AddUserFromActivityResult(userMaps, selectedNodes);
                    // 2.操作界面
                    ViewGroup twoLevelItemViewGroup = (ViewGroup) rootLayout
                            .findViewWithTag(clickedViewReferenceMap);
                    ViewGroup twoLevelUserContainerLayout = (ViewGroup) twoLevelItemViewGroup
                            .findViewById(R.id.containerLayout);
                    twoLevelUserContainerLayout.removeAllViews();// 先删除子view
                    for (Map<String, Object> userMap : userMaps) {
                        ViewGroup threeLevelUserView = createViewByType(userMap);
                        setTextByLevel(threeLevelUserView, userMap, 3);
                        manageThreeLevelView(threeLevelUserView, userMap);
                        twoLevelUserContainerLayout.addView(threeLevelUserView);
                    }
                    expandOrCollapse(twoLevelItemViewGroup, true);
                    break;
                case REQUESTCODE_TEXTAREA:
                    String result = data.getExtras().getString("result");// 得到新Activity
                    // 关闭后返回的数据
                    // 1.操作数据
                    clickedViewReferenceMap.put("value", result);
                    // 2.操作界面
                    EditText editText = (EditText) rootLayout.findViewWithTag(
                            clickedViewReferenceMap).findViewById(R.id.editText_oa);
                    if (editText != null) {
                        editText.setText(result);
                    }
                    break;

                default:
                    break;
            }
        }

    }

    /**
     * 三级{value=CN=李光辉/O=sinopec, readonly=true,
     * checked=true,elementname=option, _Self_RowSet=, elementtext=李光辉}
     *
     * @param userMaps
     * @param treeNode
     */
    private void threeLevel_AddUserFromActivityResult(
            List<Map<String, Object>> userMaps, List<TreeNode> selectedNodes) {
        for (TreeNode treeNode : selectedNodes) {
            boolean isContainNode = false;
            for (Map<String, Object> userMap : userMaps) {
                if (treeNode.getName().equals(userMap.get("elementtext"))) {
                    isContainNode = true;
                }
            }
            if (!isContainNode) {
                Map<String, Object> userMap = new HashMap<String, Object>();
                userMap.put("value", treeNode.getId());
                userMap.put("elementtext", treeNode.getName());
                userMap.put("readonly", "false");
                userMap.put("checked", "true");
                userMaps.add(userMap);
            }
        }
    }

    /**
     * 创建一个空白view
     *
     * @return
     */
    private View createBlankView() {
        DisplayMetrics outMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(outMetrics);
        int heigth = (int) TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP, 10, outMetrics);
        LinearLayout.LayoutParams blankParams = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT, heigth);
        View view = new View(this);
        view.setLayoutParams(blankParams);

        return view;
    }

    private ViewGroup createViewByType(Map<String, Object> map) {
        ViewGroup view = null;
        LayoutInflater inflater = getLayoutInflater();
        // if (!"select".equals(map.get("elementname"))) {
        // 如果第二级的elementname 不是select

        String type = (String) map.get("type");
        if ("radio".equals(type)) {
            view = (ViewGroup) inflater.inflate(R.layout.oa_approval_toggle,
                    rootLayout, false);
        } else if ("user".equals(type) || "group".equals(type)) {
            view = (ViewGroup) inflater.inflate(
                    R.layout.oa_approval_user_header, rootLayout, false);
        } else if ("textarea".equals(type) || "text".equals(type)) {
            view = (ViewGroup) inflater.inflate(R.layout.oa_approval_textarea,
                    rootLayout, false);
        } else if ("label".equals(type)) {// <input>
            view = (ViewGroup) inflater.inflate(R.layout.oa_approval_input,
                    rootLayout, false);
        } else {
            String elementname = (String) map.get("elementname");
            if ("select".equals(elementname)) {
                view = (ViewGroup) inflater.inflate(R.layout.oa_approval_input,
                        rootLayout, false);
            }
            // else if ("option".equals(elementname)) {
            // view = (ViewGroup)
            // inflater.inflate(R.layout.oa_approval_user_item,
            // rootLayout, false);
            // }
            //
            else {
                view = (ViewGroup) inflater.inflate(
                        R.layout.oa_approval_user_item, rootLayout, false);
                String name = (String) map.get("value");
                if ("收文管理".equals(name) || "行政收文".equals(name)
                        || "党委收文".equals(name)) {
                    shouwenViews.add(view);
                } else if ("发文正式".equals(name) || "发文非正式".equals(name)) {
                    wenjianViews.add(view);
                } else {
                    // view.setVisibility(View.GONE);
                }
            }
        }
        // }

        return view;
    }

    @Override
    public void onClick(View v) {

        int id = v.getId();
        if (v == mTitleBar.getLogoView()) {
            BaseApp.actManager.removeActivity(TAG);

        }
    }

    /**
     * 次监听，只负责控制View展开隐藏，以及改变展开隐藏时的相关View的样式，其他点击事件的处理，在各自的LevelView中
     *
     * @author XinQing
     */
    private class OnHierarchyViewClickListener implements OnClickListener {

        @Override
        public void onClick(View v) {

            ViewGroup parentGroup = (ViewGroup) v.getParent();
            if (parentGroup.getChildCount() >= 1) {
                View containerView = parentGroup.getChildAt(1);
                // 控制子view显示隐藏
                boolean isExpand = containerView.getVisibility() == View.GONE;
                expandOrCollapse(parentGroup, isExpand);
                // 一级菜单联动
                Object tag = parentGroup.getTag();
                if (tag != null && tag instanceof Map) {
                    Map<String, Object> levelMap = (Map<String, Object>) tag;
                    if (getLevel(levelMap) == 1) {// 处理一级View点击事件
                        clickOneLevelView(levelMap, isExpand);
                    }
                }

            }
        }

        /**
         * 一级View点击
         *
         * @param levelMap
         * @param isExpand
         */
        private void clickOneLevelView(Map<String, Object> levelMap,
                                       boolean isExpand) {
            if (relatedSwitchMap != null) {

                // return ;
                // }
                String value = (String) levelMap.get("value");
                String[] closeValues = relatedSwitchMap.get(value);
                if (closeValues != null) {
                    for (String closeValue : closeValues) {
                        Map<String, Object> closeMap = findMapByValue(
                                operationData, closeValue);
                        Log.i("", "---------title：" + closeMap.get("title"));
                        ViewGroup oneLevelView = (ViewGroup) rootLayout
                                .findViewWithTag(closeMap);
                        if (isExpand) {
                            expandOrCollapse(oneLevelView, !isExpand);
                        }
                    }
                }
            } else {
                String value = (String) levelMap.get("value");
                Map oneMap = noselectSwitchMap.get(value);

                ViewGroup oneLevelView = (ViewGroup) rootLayout
                        .findViewWithTag(oneMap);
                if (isExpand) {
                    // expandOrCollapse(oneLevelView, !isExpand);

                }
            }
        }
    }

    private void expandOrCollapse(ViewGroup itemViewGroup, boolean isExpand) {
        if (itemViewGroup.getChildCount() >= 1) {
            // 1.控制容器View显示或隐藏
            View containerView = itemViewGroup.getChildAt(1);
            if (isExpand) {
                containerView.setVisibility(View.VISIBLE);
            } else {
                containerView.setVisibility(View.GONE);
            }
            // 2.控制stateView变化
            View stateView = itemViewGroup.findViewById(R.id.state_view);
            if (stateView != null) {
                String actionViewTag = (String) stateView.getTag();
                if ("image_arrow".equals(actionViewTag)) {
                    if (stateView instanceof ImageView) {
                        ImageView stateImageView = (ImageView) stateView;
                        stateImageView
                                .setImageResource(isExpand ? R.drawable.oa_arrow_top_blue
                                        : R.drawable.oa_arrow_down_blue);
                    }
                } else if ("toggle_button".equals(actionViewTag)) {
                    if (stateView instanceof ToggleButton) {
                        ToggleButton stateToggleButton = (ToggleButton) stateView;
                        if (isExpand) {
                            stateToggleButton.toggleOn();
                        } else {
                            stateToggleButton.toggleOff();
                        }
                    }
                }
            }
        }
    }

    /**
     * 获取level
     */
    private int getLevel(Map<String, Object> levelMap) {
        Map<String, Object> parentMap = (Map<String, Object>) levelMap
                .get(TaskDataParser.OPERATION_KEY_PARENT);
        if (parentMap == null) {
            return 1;
        } else {
            return getLevel(parentMap) + 1;
        }
    }

    private Map<String, Object> findMapByValue(
            List<Map<String, Object>> levelMaps, String value) {
        for (Map<String, Object> map : levelMaps) {
            List<Map<String, Object>> childMaps = (List<Map<String, Object>>) map
                    .get(TaskDataParser.OPERATION_KEY_CHILD);
            if (value.equals(map.get("value"))) {
                return map;
            } else if (childMaps != null && childMaps.size() > 0) {
                findMapByValue(childMaps, value);
            }
        }
        return null;
    }

}
